package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.query.TravelCommendQuery;
import cn.wolfcode.trip.base.query.TravelQuery;
import cn.wolfcode.trip.base.service.IStrategyTravelService;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 游记资源控制器
 */
@RestController
@RequestMapping("travels")
public class TravelController {
    @Autowired
    private IStrategyTravelService strategyTravelService;

    @Autowired
    ITravelService travelService;

    @Autowired
    ITravelCommendService commendService;

    @PostMapping
    public JSONResult save(Travel travel){
        //设置作者
        travel.setAuthor(UserContext.getCurrentUser());
        travelService.save(travel);
        return new JSONResult();
    }

    @PutMapping("/{id}")
    public JSONResult update(Travel travel){
        travelService.update(travel);
        return new JSONResult();
    }

    @PutMapping("/{travelId}")
    public JSONResult updateShowNum(Long travelId){
        travelService.updateShowNum(travelId);
        return new JSONResult();
    }

    @GetMapping("/{id}")
    public Travel getById(@PathVariable Long id){
        return travelService.getById(id);
    }

    @GetMapping("/travelNum/{userId}")
    public int getByUserId(Long userId){
        return travelService.getByUserId(userId);
    }


    /**
     * 查询所有游记列表(分页)
     * @param qo
     * @return
     */
    @GetMapping
    public PageInfo listTravels(TravelQuery qo){
        //发布状态
        qo.setState(Travel.STATE_RELEASE);
        //公开的
        qo.setIsPublic(true);
        //按照发布间倒序
        qo.setOrderBy("t.releaseTime desc");
        return travelService.query(qo);
    }


    @GetMapping("commends")
    public PageInfo listCommends(TravelCommendQuery qo){
        //按照发布间倒序
        qo.setOrderBy("schedule desc");
        return commendService.queryForApp(qo);
    }

    /**
     * 获取  大家都在看 的游记
     * @param strategyId
     * @return
     */
    @GetMapping("/strategys/{strategyId}")
    public JSONResult listStrategyTravels(@PathVariable Long strategyId){
        JSONResult jsonResult=new JSONResult();
         try {
             List<Travel> travels = strategyTravelService.queryTravelsByStrategyId(strategyId);
             jsonResult.setResult(travels);
        } catch (Exception e) {
            e.printStackTrace();
             jsonResult.mark("error");
        }
        return jsonResult;
    }

}
